import * as monaco from 'monaco-editor';
import 'monaco-editor/esm/vs/language/typescript/monaco.contribution';
import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';

// 预加载 workers
self.MonacoEnvironment = {
  getWorker(_, label) {
    if (label === 'json') {
      return new jsonWorker();
    }
    if (label === 'css' || label === 'scss' || label === 'less') {
      return new cssWorker();
    }
    if (label === 'html' || label === 'handlebars' || label === 'razor') {
      return new htmlWorker();
    }
    if (label === 'typescript' || label === 'javascript') {
      return new tsWorker();
    }
    return new editorWorker();
  }
};

// 延迟初始化 TypeScript 配置
export const initializeTypeScriptDefaults = () => {
  try {
    if (monaco.languages.typescript && monaco.languages.typescript.javascriptDefaults) {
      // 配置 Monaco Editor 的默认设置
      monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
        noSemanticValidation: false,
        noSyntaxValidation: false,
        noSuggestionDiagnostics: false
      });

      // 配置 TypeScript 编译器选项
      monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
        target: monaco.languages.typescript.ScriptTarget.ESNext,
        allowNonTsExtensions: true,
        moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
        module: monaco.languages.typescript.ModuleKind.ESNext,
        noEmit: true,
        esModuleInterop: true,
        jsx: monaco.languages.typescript.JsxEmit.React,
        allowJs: true,
        typeRoots: ["node_modules/@types"],
        strict: true,
        types: ["node", "react"]
      });
      
      console.log('TypeScript 默认配置已初始化');
      return true;
    } else {
      console.warn('TypeScript 语言服务未就绪');
      return false;
    }
  } catch (error) {
    console.error('初始化 TypeScript 配置失败:', error);
    return false;
  }
};

// 尝试立即初始化，如果失败则稍后重试
if (!initializeTypeScriptDefaults()) {
  // 延迟重试
  setTimeout(initializeTypeScriptDefaults, 100);
}

// 添加类型定义
const libSource = `
  declare module "*.worker?worker" {
    const workerConstructor: {
      new (): Worker;
    };
    export default workerConstructor;
  }
  
  interface Window {
    MonacoEnvironment: any;
  }
`;

// 添加默认类型库
monaco.languages.typescript.javascriptDefaults.addExtraLib(
  libSource,
  'global.d.ts'
);

// 预加载常用的 npm 包类型定义
const loadTypeDefs = async () => {
  try {
    const response = await fetch('https://cdn.jsdelivr.net/npm/@types/react@latest/index.d.ts');
    const reactTypes = await response.text();
    monaco.languages.typescript.javascriptDefaults.addExtraLib(
      reactTypes,
      'file:///node_modules/@types/react/index.d.ts'
    );
  } catch (error) {
    console.warn('无法加载 React 类型定义:', error);
  }
};

loadTypeDefs();

console.log('Monaco编辑器工作线程和类型定义已初始化');